/*
    created: 2023/4/5
    filename: Singleton.cpp
    author: 李东霖
    purpose: 单例模式的演示代码

*/

#include"Singleton.h"
#include<iostream>
//测试单例
Singleton* Singleton::m_pStatic = NULL; 
Singleton* Singleton::GetInstancePtr() 
{ 
 if (NULL == m_pStatic) 
 { 
 m_pStatic = new Singleton(); 
 } 
 return m_pStatic; 
} 
Singleton Singleton::GetInstance() 
{ 
 return *GetInstancePtr(); 
} 
void Singleton::Test() 
{ 
 std::cout << "Test!\n"; 
}

/*
//实现c++11标准，返回static修饰的变量
template <class T>
Singleton<T>::Singleton()
{
    std::cout<<"实例化了一个T类型的对象在你第一次调用GetInstance方法之后"<<std::endl;
}
template <class T>
T* Singleton<T>::GetInstance()
{
    static T* instance = new T; //只执行一次 
    return instance;
}


//懒汉式
template <class T,bool is_thread_safe>
T* LazySingleton<T,is_thread_safe>::GetInstance()
{
    if(!is_thread_safe)//不安全
    {
        if(t_ == nullptr)
        {   
            t_ = new T;
        }
        return t_;
    }
    if(t_ == nullptr)
    {
        //上锁
        unique_lock<mutex> unique_locker(mtx_);
            if (t_ == nullptr)
                t_ = new T;
            return *t_;       
    }
}

 template <class T,bool is_thread_safe>
LazySingleton<T,is_thread_safe>::~LazySingleton()
 {
    //使用了内置指针，需要释放
    if(t_ != nullptr)
    {
        delete t_;
        t_ = nullptr;
    }
 }

//饿汉式  
template<class T>
T* EagerSingleton<T>::GetInstance()
{
    return t_;
}
*/